<template>
  <div class="app-container">
    <el-input v-model="listQuery.search" placeholder="请输入菜单名称" style="width:200px;margin-bottom: 10px;" clearable></el-input>
    <el-select filterable v-model="listQuery.status" placeholder="请选择菜单状态">
      <el-option v-for="item in optionsStatus" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
    <el-select filterable v-model="listQuery.level" placeholder="请选择菜单层级">
      <el-option v-for="item in optionsLevel" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
    <el-select filterable v-model="listQuery.type" placeholder="请选择菜单类型">
      <el-option v-for="item in optionsType" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
    <el-button type="primary" @click="getList" icon="el-icon-search"   style="margin-bottom: 10px;">搜索</el-button>

    <el-button   class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate()" style="margin-bottom: 10px;">
      添加
    </el-button>
    <el-button class="filter-item" type="primary" @click="cache()" style="margin-left: 0;margin-bottom: 10px;">缓存菜单数据</el-button>

    <el-table :data="menuList" style="margin-bottom: 20px;" row-key="id" border :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="menu_id" label="菜单编号" > </el-table-column>
      <el-table-column prop="menu_name" label="菜单名称" > </el-table-column>
      <el-table-column prop="menu_key" label="菜单路由" > </el-table-column>
      <el-table-column prop="add_time" label="添加时间" > </el-table-column>
      <el-table-column prop="status" label="状态" >
        <template slot-scope="scope">
          {{ scope.row.status === 1?'显示':'' }}
          {{ scope.row.status === 2?'隐藏':'' }}
        </template>
      </el-table-column>
      <el-table-column prop="parent_id" label="父级编号" > </el-table-column>
      <el-table-column prop="level" label="层级" >
        <template slot-scope="scope">
          {{ scope.row.level === 1?'一级':'' }}
          {{ scope.row.level === 2?'二级':'' }}
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" > </el-table-column>
      <el-table-column prop="type" label="类型" >
        <template slot-scope="scope">
          {{ scope.row.type === 1?'公会菜单':'' }}
          {{ scope.row.type === 2?'厅菜单':'' }}
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="图标地址" ></el-table-column>
      <el-table-column min-width="280" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>
            编辑
          </el-button>
<!--          <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.perPage" @pagination="getList"/>
<!--    v-show="total>0"-->

    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="handleDialogClose">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="120px" style="width: 400px; margin: 0 auto;">
        <el-form-item label="菜单父级编号">
          <el-input v-model="form.parent_id" placeholder="菜单父级编号"/>
        </el-form-item>
        <el-form-item label='菜单名称' prop="menu_name">
          <el-input v-model="form.menu_name" placeholder="请输入菜单名称"/>
        </el-form-item>
        <el-form-item label="菜单key值" prop="menu_key">
          <el-input v-model="form.menu_key" placeholder="请输入菜单key值"/>
        </el-form-item>
        <el-form-item :label="tempDesc.type" prop="type">
          <el-select filterable v-model="form.type" class="filter-item" :placeholder="'请选择' + tempDesc.type" style="width: 280px;"
                     clearable>
            <el-option v-for="item in menuTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="tempDesc.icon" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入图标"/>
        </el-form-item>
        <el-form-item label="菜单层级" prop="level">
          <el-input v-model="form.level" type="number" placeholder="请输入菜单层级"/>
        </el-form-item>
        <el-form-item label="菜单状态" prop="status">
          <el-select filterable v-model="form.status" class="filter-item" placeholder="请选择菜单状态" style="width: 280px;"
                     clearable>
            <el-option v-for="item in menuStatus" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单排序" prop="sort">
          <el-input v-model="form.sort" type="number" oninput="if(value>100)value=100;if(value<1)value=1" placeholder="请输入菜单排序"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { saveMenu, deleteMenu, treeMenu, updateMenu, cacheMenu } from '@/api/system/menu'

  import treeTable from '@/components/TreeTable'
  import { validateCh } from '@/utils/validate'

  // 常量title
  const tempDesc = {
    'id': '',
    'parentId': '',
    'menu_key': '菜单key值',
    'menu_name': '名称',
    'level': '排序',
    'icon': '图标',
    'type': '类型',
    'status': '状态',
    'parent_id': '上级菜单'
  }
  const menuTypeOptions = [
    { key: '1', display_name: '公会菜单' },
    { key: '2', display_name: '厅菜单' }
  ]
  const menuStatus = [
    { key: '1', display_name: '显示' },
    { key: '2', display_name: '隐藏' }
  ]

  export default {
    components: { treeTable },
    data() {
      const _validateCh = (rule, value, callback) => {
        if (!!value && validateCh(value)) {
          callback(new Error('不能包含中文'))
        }
        callback()
      }
      return {
        expandAll: false,
        // expandAll: true, // 是否全部展开
        expandAllTitle: '展开全部',
        tempDesc: tempDesc,
        listLoading: true,
        total: 0,
        listQuery: {
          page: 1,
          perPage: 10
        },
        columns: [
          {
            label: '菜单名称',
            key: 'title',
            width: 220,
            expand: true,
            align: 'left',
            headerAlign: 'center'
          },
          {
            label: '菜单key值',
            key: 'menu_key'
          },
          {
            label: tempDesc.type,
            key: 'type'
          },
          {
            label: '状态',
            key: 'status'
          },
          {
            label: tempDesc.icon,
            key: 'icon'
          },
          {
            label: '菜单层级',
            key: 'level'
          }
        ],
        menuList: [],
        menuTree: [],// 树形菜单
        menuIcon:[
          { key: '1', display_name: 'el-icon-edit' },{ key: '2', display_name: 'el-icon-share' },
          { key: '3', display_name: 'el-icon-s-tools' },{ key: '4', display_name: 'el-icon-user-solid' },
          { key: '5', display_name: 'el-icon-s-help' },{ key: '6', display_name: 'el-icon-picture' },
          { key: '7', display_name: 'el-icon-message-solid' },{ key: '8', display_name: 'el-icon-s-order' },
          { key: '9', display_name: 'el-icon-s-home' },{ key: '10', display_name: 'el-icon-s-marketing' },
        ],
        dialogFormVisible: false,
        dialogStatus: '',
        titleMap: {
          update: '编辑',
          create: '增加'
        },
        form: {
          'menu_id': undefined,
          'parentId': undefined,
          'menu_key': undefined,
          'menu_name': undefined,
          'level': undefined,
          'icon': undefined,
          'type': undefined,
          'status': undefined,
          'parent_id': undefined,
          'sort': undefined
        },
        menuTypeOptions,
        menuStatus,
        optionsStatus: [{value:undefined,label: '全部菜单状态'},{value: '1',label: '显示'},{value: '2',label: '隐藏'}],
        optionsLevel: [{value:undefined,label: '全部菜单层级'},{value: '1',label: '一级'},{value: '2',label: '二级'}],
        optionsType: [{value:undefined,label: '全部菜单类型'},{value: '1',label: '公会菜单'},{value: '2',label: '厅菜单'}],
        rules: {
          menu_name: [
            { required: true, message: '请输入菜单名称', trigger: 'blur' },
            { min: 1, max: 25, message: '长度在 1 到 50 个字符', trigger: 'blur' }
          ],
          menu_key: [
            { required: true, message: '请输入菜单key值', trigger: 'blur' }
          ],
          parent_id: [
            { required: true, message: '菜单父级编号', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择' + tempDesc.type, trigger: 'blur' }
          ],
          status: [
            { required: true, message: '请选择状态', trigger: 'blur' }
          ],
          level: [
            { required: true, message: '请输入菜单层级', trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '请输入菜单层级', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      if (this.global_checkBtnPermission(['sys:menu:add', 'sys:menu:addsub', 'sys:menu:edit', 'sys:menu:delete'])) {
        this.columns.push({ label: '操作', key: 'operation', width: 320 })
      }
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        let urlData = '?';
        if(this.listQuery.page){ urlData = urlData + `page=${this.listQuery.page}&`}
        if(this.listQuery.perPage){ urlData = urlData + `perPage=${this.listQuery.perPage}`}
        if(this.listQuery.search){ urlData = urlData + `&search=${this.listQuery.search}`}
        if(this.listQuery.status){ urlData = urlData + `&status=${this.listQuery.status}`}
        if(this.listQuery.level){ urlData = urlData + `&level=${this.listQuery.level}`}
        if(this.listQuery.type){ urlData = urlData + `&type=${this.listQuery.type}`}

        treeMenu(urlData).then(response => {

          this.menuList = response.data.list
          this.total = response.data.meta.total;

          this.listLoading = false
        })
      },
      handleCreate(row) {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true

        if (!row) { // 一级菜单
          this.form.level = '1'// 默认一级菜单
          this.form.parentId = '0'
        }
        if (row) { // 子菜单
          this.form.level = parseInt(row.level) + 1
          this.form.parentId = row.id
          this.form.parent_id = row.menu_name;
        }
      },
      handleUpdate(row) {
        this.form = []
        // this.form = Object.assign({}, row) // copy obj  此方法在这里暂时不能使用，会出错 -> 有多余参数
        this.form.menu_id = row.menu_id
        this.form.parent_id = row.parent_id
        this.form.menu_name = row.menu_name
        this.form.menu_key = row.menu_key
        this.form.type = row.type
        this.form.status = row.status
        this.form.icon = row.icon
        this.form.level = row.level
        this.form.sort = row.sort

        this.dialogStatus = 'update'
        this.dialogFormVisible = true

        let parentNode = this.findTreeNode(row.parentId)
        if (parentNode) {
          this.form.parent_id = parentNode.menu_name
        }

        this.form = Object.assign({}, this.form)
      },
      handleDelete(row) {
        deleteMenu(row.id).then(response => {
          if (response.code === 0) {
            this.getList()
            this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
          }
        })
      },
      submitForm() {
        // this.form.parent_id = undefined;
        this.$refs['dataForm'].validate(valid => {
          if (valid && this.dialogStatus === 'create') {
            saveMenu(this.form).then(response => {
              if (response.code === 200) {
                this.getList()
                this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
                this.dialogFormVisible = false
              } else {
                this.$message({
                message: response.message,
                type: 'error'
            });
              }
            })
          }else if(valid && this.dialogStatus === 'update'){
            updateMenu(this.form).then(response => {
              if (response.code === 200) {
                this.getList()
                this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
                this.dialogFormVisible = false
              } else {
                this.$message({
                message: response.message,
                type: 'error'
            });
              }
            })
          }
        })
      },
      cache(){
        cacheMenu(this.form).then(response => {
          this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
        })
      },
      findTreeNode(id) {
        let node = this._.find(this.menuList, { id: parseInt(id) })
        return node
      },
      handleExpand() {
        this.expandAll = !this.expandAll
        this.expandAllTitle = this.expandAll ? '折叠全部' : '展开全部'
      },
      resetForm() {
        this.form = {
          'id': undefined,
          'parentId': undefined,
          'menu_key': undefined,
          'menu_name': undefined,
          'level': undefined,
          'icon': undefined,
          'type': undefined,
          'status': undefined,
          'sort': undefined,
          'parent_id': undefined
        }
      },
      // 监听dialog关闭时的处理事件
      handleDialogClose() {
        if (this.$refs['dataForm']) {
          this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
        }
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>

  .app-container /deep/ .el-date-editor.el-input{
    margin-bottom: 10px;
  }
  .app-container /deep/ .el-select{
    margin-bottom: 10px;
  }
</style>
